<template>
  <el-select
    style="width: 100%"
    ref="treeSelect"
    v-model="selectedValue"
    filterable
    clearable
    :placeholder="placeholder"
    :filter-method="selectFilterData"
    @clear="clearHandle"
  >
    <el-option :value="selectedValue" :label="selectedLabel">
      <el-tree
        id="tree-option"
        ref="selectTree"
        :node-key="treeProps.value"
        :data="options"
        :props="treeProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      />
    </el-option>
  </el-select>
</template>

<script>
export default {
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    placeholder: {
      type: String,
      default: "",
    },
    options: {
      type: Array,
      default: () => [],
    },
    treeProps: {
      type: Object,
      default: () => {
        return {
          value: "id", // ID字段名
          label: "label", // 显示名称
          children: "children", // 子级字段名
        };
      },
    },
  },
  data() {
    return {
      selectedLabel: "",
    };
  },
  computed: {
    selectedValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
  },
  watch: {
    selectedValue() {
      this.initHandle();
    },
  },
  methods: {
    initHandle() {
      this.$nextTick(() => {
        const selectedValue = this.selectedValue;
        if (selectedValue !== null) {
          const node = this.$refs.selectTree.getNode(selectedValue);
          this.selectedLabel = node ? node.data[this.treeProps.label] : "";
        } else {
          this.clearHandle();
        }
      });
    },
    handleNodeClick(node) {
      this.selectedValue = node[this.treeProps.value];
      this.selectedLabel = node[this.treeProps.label];
      this.$refs.treeSelect.blur();
      this.selectFilterData("");
    },
    selectFilterData(val) {
      this.$refs.selectTree.filter(val);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data[this.treeProps.label].indexOf(value) !== -1;
    },
    clearHandle() {
      this.selectedValue = "";
      this.selectedLabel = "";
      this.clearSelected();
    },
    clearSelected() {
      const allNode = document.querySelectorAll("#tree-option .el-tree-node");
      allNode.forEach((element) => element.classList.remove("is-current"));
    },
  },
};
</script>

<style lang="scss" scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  padding: 0;
  background-color: #fff;
  height: auto;
}

::v-deep {
  .el-tree-node.is-current > div:first-child,
  .el-tree-node__content:focus {
    background-color: #ecf5ff;
    color: #409eff;
  }
}
</style>
